package com.zy.ivideo.controller;

import com.zy.ivideo.token.PassToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
@Api(value = "文件上传下载接口", description = "该模块提文件上传下载服务", tags = "文件上传下载模块")
public class FileController {

    @PassToken
    @ApiOperation(value = "上传文件", notes = "上传文件", httpMethod = "POST")
    @PostMapping("/upload")
    public org.springframework.http.ResponseEntity<String> uploadFile(@RequestParam("file")
                                                                          @ApiParam(value = "上传的文件", name = "file", required = true)
                                                                          MultipartFile file) {
        String dirPath="uploads/";
        File dir=new File(dirPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        Path path = Paths.get("uploads/" + file.getOriginalFilename());
        try{
            byte[] bytes = file.getBytes();
            Files.write(path,bytes);
            return org.springframework.http.ResponseEntity.ok("File uploaded successfully:"+file.getOriginalFilename());
        }catch (IOException e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed:"+e.getMessage());
        }
    }

    @PassToken
    @ApiOperation(value = "下载文件", notes = "下载文件", httpMethod = "GET")
    @GetMapping("/download/{filename}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable
                                                               @ApiParam(value = "下载的文件名", name = "filename", required = true)
                                                               String filename) {
        File file=new File("uploads/"+filename);
        if(!file.exists()){
            return ResponseEntity.notFound().build();
        }
        FileSystemResource resource=new FileSystemResource(file);
        HttpHeaders headers=new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename="+filename);
        return ResponseEntity.ok().headers(headers).body(resource);
    }
}
